import React from 'react';
import '../../style/filePath.less';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

/*
* props属性：
* path      受控数据【数据结构见下面】
* onClick   点击事件回调【参数：newPath: 最新的path。pathKey: 当前点击的id。 e: 事件对象】
* homeTab   home图标右边的文字，与home一样不属于可变化的路径。点击后分别传id:"home","homeTab"【string】
* search    搜索文档时，若想要在路径中配合显示，则使用此属性【boolean】
* searchValue  若使用search属性，需将此属性传入搜索值【string】
* className 自定义样式【string】
*
* 数据结构：
* path = [
*  {
*     id: id      必需 string
*     text: text  必需 string
*  },
*  ...
* ]
*
* 说明：
*     1.关于搜索
*        搜索回车后，路径上显示了“xxx搜索结果”，这时点击home，想要使路径显示恢复正常，需要将searchValue的值置为空。
*
* */


class DocFilePath extends React.Component {
   // 检查传入的格式数据是否正确，并检查id是否唯一
   checkData = (path) => {
      let commonMsg = '公共组件< DocFilePath > props错误：';
      let repeat = [];
      path.forEach((i) => {
         if (repeat.includes(i.id)) // 检查id是否重复
         {
            this.throwError(`${commonMsg}属性path：有重复的目录id`);
         }
         ['id', 'text'].forEach((j) => {
            !(typeof i[j] === 'string' && i[j].length > 0) && this.throwError(`${commonMsg}属性path：${j}不合法`);
         });
         repeat.push(i.id);
      });
   };

   // 抛出异常
   throwError = (text) => {
      throw new Error(text);
   };

   // 点击home
   clickHome = (e) => {
      let { onClick } = this.props;
      typeof onClick === 'function' && onClick([], 'home', e);
   };

   // 点击homeTab
   clickHomeTab = (e) => {
      let { onClick } = this.props;
      typeof onClick === 'function' && onClick([], 'homeTab', e);
   };

   // 点击事件回调
   clickItem = (pathKey, e) => {
      const { onClick, path } = this.props;
      let newPath = [...path],
length = path.length;
      if (pathKey !== path[length - 1].id) {
         for (let i = length - 1; i >= 0; i--) {
            if (path[i].id !== pathKey) {
               newPath.pop();
            } else {
               break;
            }
         }
      }
      typeof onClick === 'function' && onClick(newPath, pathKey, e); // 传入参数：最新的path，当前点击的id，e
   };


   renderItem = () => {
      let { path, search, searchValue } = this.props;
      let isSearch = false,
result;
      this.checkData(path); // 检查数据是否OK
      search === true && typeof searchValue === 'string' && searchValue.length > 0 && (isSearch = true); // 判断当前是否在搜索

      // isSearch
      if (isSearch) {
         let label = getLabel(513990, '的搜索结果');
         let string = `${label === 'Search results for' ? label : ''}"${searchValue}"${label === 'Search results for' ? '' : label}`;
         result = <PathItem ecId={`${this && this.props && this.props.ecId || ''}_PathItem@bhpb81`} search={true} text={string} />;
      } else {
         result = path.length > 0 && path.map(i => (
            <PathItem ecId={`${this && this.props && this.props.ecId || ''}_PathItem@f8pnip@${i.text}`} key={i.id} pathKey={i.id} text={i.text} onClick={this.clickItem} />
         ));
      }

      return result;
   };

   render() {
      const { className, style, homeTab } = this.props;

      return (
         <div className={`WeaDoc-FilePath${className ? ` ${className}` : ''}`} style={style}>
            <div>
               <div className="Path-item">
                  <i className="home icon-coms-LargeArea add-addtabicon-home" onClick={this.clickHome} />
                  <span className="homeTab" onClick={this.clickHomeTab}>{ homeTab }</span>
               </div>
               { this.renderItem() }
            </div>
         </div>
      );
   }
}

// 子组件Item
class PathItem extends React.Component {
   clickHandle = (e) => {
      const { onClick, pathKey } = this.props;
      typeof onClick === 'function' && onClick(pathKey, e);
   };

   render() {
      const { text, search } = this.props;
      return (
         <div className="Path-item" onClick={this.clickHandle}>
            <i className="arrow icon-coms-organization-right add-addtabicon-caretright" />
            <span className={search ? 'search' : 'text'} title={text}>{ text }</span>
         </div>
      );
   }
}


export default DocFilePath;
